/**
 * 				Server.java
 *				------------
 *		
 *   Author:	bin04017
 *   ID:		bin04017
 *	 Created:	24.01.2007
 *	 Project:	Mochito
 *	 Package:	tools.server
 *	 Usage:		
 */
package mochito.tools.serverPackage.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import mochito.tools.clipboard.AccessClipboard;


/**
 * @author bin04017
 * 
 */
public class Server implements Runnable {

	private boolean running = true;
	
	private ServerSocket serverSocket = null;

	public Server(ServerSocket socket) {
		this.serverSocket = socket;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		Socket socket = null;
		while (running) {
			try {
				socket = serverSocket.accept();
			    BufferedReader in = new BufferedReader(
						    new InputStreamReader(
						    		socket.getInputStream()));

			    String inputLine = "";
			    String fullLine = "";
				while ((inputLine = in.readLine()) != null) {
				 	fullLine += inputLine;
				}
			    in.close();
			    socket.close();
			    AccessClipboard.writeToClipboard(fullLine);
			} catch (Exception e) {
				try {
					if(socket != null && socket.isConnected()){
						socket.close();
					}
					socket = null;
				} catch (IOException e1) {

				}
			}
		}
	}

	/**
	 * @return the running
	 */
	public boolean isRunning() {
		return running;
	}

	/**
	 * @param running the running to set
	 */
	public void stop() {
		try {
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.running = false;
	}

}
